package com.market.member.service.login;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.model.dto.LoginReqDTO;
import com.block.common.model.dto.NewMemberDTO;
import com.block.common.service.IMemberCommonService;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.MemberBaseInfo;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.block.sms.service.IQuickLoginService;
import com.market.member.enums.UserRegTypeEnum;
import com.market.member.enums.UserTypeEnum;
import com.market.member.model.dto.LoginResultDTO;
import com.market.member.service.ILoginTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 一键登录
 */
@Slf4j
@Service
public class QuickLoginServiceImpl extends ILoginTypeService {

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IQuickLoginService quickLoginService;
    @Resource
    MemberBaseInfoMapper memberBaseInfoMapper;

    @Override
    public ResponseVo toLogin(LoginReqDTO loginReqDTO) {

        String loginCode = loginReqDTO.getLoginCode();

        String mobile = "";
        try {
            mobile = quickLoginService.getMobile(loginCode);
            if (StrUtil.isEmpty(mobile)) {
                return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "登陆异常，请使用其他方式登陆");
            }
        }catch (Exception exception){
            // TODO: 2023/8/25 消息通知
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "登陆失败，请使用其他方式登陆");
        }

        MemberBaseInfo memberInfo = memberBaseInfoMapper.getBaseUserInfoByPhoneLock(mobile);
        boolean isNewMember = false;
        if (memberInfo == null){

            NewMemberDTO newMemberDTO = new NewMemberDTO();
            newMemberDTO.setMobile(mobile);
            newMemberDTO.setChannelCode(loginReqDTO.getChannelCode());
            newMemberDTO.setChannelName(loginReqDTO.getChannelName());
            newMemberDTO.setRegAppCode(loginReqDTO.getAppCode());
            newMemberDTO.setRegReqIP(loginReqDTO.getReqIp());
            newMemberDTO.setType(UserTypeEnum.NORMAL.getValue());
            newMemberDTO.setRegType(UserRegTypeEnum.NORMAL.getValue());

            memberInfo = memberCommonService.saveNewMemberInfo(newMemberDTO);
            if (ObjectUtil.isEmpty(memberInfo)){
                return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "注册失败，请重试");
            }
            isNewMember = true;
        }

        LoginResultDTO loginResultDTO = new LoginResultDTO();
        loginResultDTO.setUid(memberInfo.getUid());
        loginResultDTO.setNewMember(isNewMember);
        loginResultDTO.setMemberBaseInfo(memberInfo);

        return new ResponseVo(AppRspCodeConstant.SUCCESS, loginResultDTO);
    }
}
